package com.xy.core.shiro;


import com.xy.user.domain.XyMenu;
import com.xy.user.domain.Xyuser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/3/19.
 */

public class LoginShiroInterceptor extends HandlerInterceptorAdapter  {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = getURI(request);
       /* if("/admin/index.do".equals(uri)||"/admin/login.do".equals(uri)){
            return true;
        }*/

        List<XyMenu> listnav = new ArrayList<XyMenu>();//导航栏
        /*Map<String, Object> map = new HashMap<String, Object>();

        XyMenu xyMenu2 = new XyMenu();
        xyMenu2.setName("店铺列表");
        listnav.add(xyMenu2);
        XyMenu xyMenu3 = new XyMenu();
        xyMenu3.setName("店铺新增");
        listnav.add(xyMenu3);
        request.getSession().setAttribute("listnav",listnav);*/

        //根据网址找到实体，并和shiro匹配是否认证，如果认证则通过
        //1 菜单限定拦截
        XyMenu xyMenu = MenuCache.getMenu_cache(uri);
        //菜单导航栏
        List<XyMenu> xyMenuList = new ArrayList<XyMenu>();
        XyMenu xyMenutest = xyMenu;
        while(xyMenutest!=null&&xyMenutest.getParentId()!=null&&!"0".equals(xyMenutest.getParentId())){
            listnav.add(xyMenutest);
//            System.out.println(xyMenutest.getName());
            xyMenutest = MenuCache.getMenuBeanById_cache(xyMenutest.getParentId());
        }
        request.getSession().setAttribute("listnav",listnav);

        Xyuser user = (Xyuser) request.getSession().getAttribute("adminuser");

        if(user!=null&&"admin".equals(user.getUsername())){
            return true;
        }


        if(xyMenu==null){//链接不是菜单内容，则不拦截
            return true;
        }
        //2、session过期，或者session用户不存在


        //3、登录拦截comments:list
        Subject currentUser2 = SecurityUtils.getSubject();
//        if(currentUser2!=null&&currentUser2.isAuthenticated()&&adminuser!=null){
        if(currentUser2!=null&&user!=null){
            //4、权限拦截
            if(currentUser2.isPermitted(xyMenu.getNameEn())){
                return true;
            }else{
                //权限不足
                response.sendRedirect(request.getContextPath()+"/admin/nopermissions.do");
                return false;
            }
        }else{
            //用户没登录
            StringBuffer sb = new StringBuffer();
            sb.append("<!DOCTYPE html>\n");
            sb.append("<html lang=\"en\">\n");
            sb.append("<head>\n");
            sb.append("<meta charset=\"UTF-8\">\n");
            sb.append("<title>Title</title>\n" );
            sb.append("</head>\n");
            sb.append("<body bgcolor=\"#FFFFFF\" text=\"#000000\">\n");
            sb.append("<script language='javascript'>top.location.href = '");
            sb.append(request.getContextPath()+"/admin/login.do");
            sb.append("'</script>\n");
            sb.append("</body>\n");
            sb.append("</html>");

            response.getWriter().print(sb.toString());
//            response.sendRedirect(request.getContextPath()+"/admin/login.do");
            return false;
        }


       /* if(currentUser2.isPermitted(menu.getNameEn())){
            return true;
        }*/

       /* Subject currentUser2 = SecurityUtils.getSubject();
        currentUser2.isPermitted("/czjcommodity/list.do");
        if(checkLogin(request)){
            Subject currentUser = SecurityUtils.getSubject();
            if(!currentUser.isAuthenticated()){
                response.sendRedirect(request.getContextPath()+"/admin/login.do");
                return false;
            }
        }*/

       /* System.out.println("preHandle:"+request.getRequestURI());
        if(checkLogin(request)){
            // 获得用户
            Xyuser adminuser = (Xyuser) request.getSession().getAttribute("adminuser");
            // 用户为null跳转到登陆页面
            if (adminuser == null) {
                response.sendRedirect(request.getContextPath()+"/admin/login.do");
                return false;
            }
        }*/

//        return false;
    }

    private boolean checkLogin(HttpServletRequest request) {

        String uri = getURI(request);
        for (String s : excludeURL) {
            if(s.equals(uri)||uri.startsWith(s)){
                return false;
            }
        }

        for (String s : includeURL) {
            if(s.equals(uri)||uri.startsWith(s)){
                return true;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("postHandle");
        super.postHandle(request, response, handler, modelAndView);
    }
    private String[] includeURL;
    private String[] excludeURL;

    public void setExcludeURL(String[] excludeURL) {
        this.excludeURL = excludeURL;
    }

    public void setIncludeURL(String[] includeURL) {
        this.includeURL = includeURL;
    }
    /**
     * 获得第三个路径分隔符的位置
     *
     * @param request
     * @throws IllegalStateException
     *             访问路径错误，没有三(四)个'/'
     *             返回${base}之后的网址 例如：/admin/index.do
     */
    private static String getURI(HttpServletRequest request)
            throws IllegalStateException {

        UrlPathHelper helper = new UrlPathHelper();
        String uri = helper.getOriginatingRequestUri(request);
        String ctxPath = helper.getOriginatingContextPath(request);
        return uri.replace(ctxPath,"");

    }
}
